<?php
/**
 * Controller Applications Users
 */
include_once 'classes/DBconnect.php';
include_once 'dao/Users.php';
class ControllerUsers
{   
	private $dbConnect;
	private $typemvc;
	private $smarty;
	private $users;
	private $messagedisplay;
	public $mvcData;
	
	/**
	 * Add connect DB
	 */
	public function __construct()
	{
		$this->users = new DaoUsers();
	}
	
	/**
	 * Validate form to the correctness of filling
	 * 
	 * @param $post array answer user
	 */
	public function validateFormRegisterUser($post)
	{
		if (empty($_POST['login'])
			|| empty($_POST["password"][0])
			|| empty($_POST["password"][1])
			|| empty($_POST['name']))
		{
			return false;
		}
		else
		{
			$_SESSION['login']=$_POST['login'];
			return true;
		}
	}
	
 
	public function logout()
	{
		session_destroy();
		Header("Location: index.php?views=login");	
	}
	
	public function loginUser($post)
	{
		if (!isset($post['ok']))
		{	
			$this->messagedisplay = 'login';
		}
		else 
		{
			if ($this->users->loginUser($post[login], md5($post[password])) == true)
			{
				$_SESSION['login'] = $post[login];
				Header("Location: index.php");
			}
			else 
			{
				$this->messagedisplay = 'nocorectdata';
			}
		}
	}
	
	public function registration($post)
	{
		if (!isset($post['ok']))
		{
			$this->messagedisplay = 'regist';
		}
		else
		{	
			$resultValidate = $this->validateFormRegisterUser($post);
			if ($resultValidate == false)
			{
				$this->messagedisplay = 'Notallfields';
			}
			else
			{
				if ($this->users->freeLogin($post[login]) == true)
				{
					if ($this->users->registerUser($post))
					{
						$this->messagedisplay = 'registerUser';
					}
				}
				else
				{
					$this->messagedisplay = 'noregisterUser';
				}
			}
			
		}
	}
	
	public function protecteds()
	{
		if ($this->users->nologout() == true)
    	{
    		$this->messagedisplay = 'protected';
    	}
    	else 
    	{
    		Header("Location: index.php?views=login");   
    	}
	}
	
	public function determinantPage($post, $get)
	{
		
		switch ($get['views']) 
			{
		    case 'login':
				$this->loginUser($post);	
			break;
		    case 'protected':
		    	$this->protecteds();
			break;
			case 'logout':
				$this->logout();
		    break;
			case 'registration':
				$this->registration($post);
			break;
			default:	
				Header("Location: index.php?views=login");	
			}		
			$this->mvcData = $this->messagedisplay;
		return $this->messagedisplay;
		
	}
	public function getMvcData() 
    { 
    	return $this->mvcData;
    } 
}